<template>
  <div class="lesson-plan-detail">
    <el-container v-loading="loading">
      <!-- 顶部操作栏 -->
      <el-header class="detail-header">
        <div class="header-content">
          <el-button @click="handleBack">
            ← 返回列表
          </el-button>
          <div class="action-buttons" v-if="lessonPlan && canEdit">
            <el-button
              type="primary"
              @click="handleEdit"
            >
              ✏️ 编辑
            </el-button>
            <el-button
              type="danger"
              @click="handleDelete"
            >
              🗑️ 删除
            </el-button>
          </div>
        </div>
      </el-header>
      
      <el-main v-if="lessonPlan">
        <div class="detail-content">
          <!-- 教案标题和基本信息 -->
          <div class="lesson-header">
            <h1 class="lesson-title">
              {{ lessonPlan.title }}
              <el-tag
                v-if="lessonPlan.status === 'draft'"
                type="info"
                class="status-tag"
              >
                草稿
              </el-tag>
              <el-tag
                v-else-if="lessonPlan.status === 'archived'"
                type="warning"
                class="status-tag"
              >
                已归档
              </el-tag>
            </h1>
            
            <div class="lesson-meta">
              <div class="meta-item">
                <span>👤</span>
                <span>作者：{{ lessonPlan.author.name }}</span>
              </div>
              <div class="meta-item">
                <span>📅</span>
                <span>创建时间：{{ formatDate(lessonPlan.createdAt) }}</span>
              </div>
              <div class="meta-item">
                <span>🕒</span>
                <span>更新时间：{{ formatDate(lessonPlan.updatedAt) }}</span>
              </div>
              <div class="meta-item">
                <span>📋</span>
                <span>版本：v{{ lessonPlan.version }}</span>
              </div>
            </div>
            
            <div class="lesson-stats">
              <div class="stat-item">
                <span>👁️</span>
                <span>{{ lessonPlan.views || 0 }} 次浏览</span>
              </div>
              <div class="stat-item">
                <span>⭐</span>
                <span>{{ lessonPlan.likes || 0 }} 个赞</span>
              </div>
              <div class="stat-item">
                <span>💬</span>
                <span>{{ lessonPlan.comments?.length || 0 }} 条评论</span>
              </div>
            </div>
          </div>
          
          <!-- 分类信息 -->
          <div class="lesson-categories">
            <el-space wrap>
              <el-tag type="primary" size="large">
                📚 {{ lessonPlan.subject }}
              </el-tag>
              <el-tag type="success" size="large">
                🎓 {{ lessonPlan.grade }}
              </el-tag>
              <el-tag type="warning" size="large">
                📝 {{ lessonPlan.courseType }}
              </el-tag>
            </el-space>
          </div>
          
          <!-- 标签 -->
          <div class="lesson-tags" v-if="lessonPlan.tags && lessonPlan.tags.length > 0">
            <el-space wrap>
              <el-tag v-for="tag in lessonPlan.tags" :key="tag">
                🏷️ {{ tag }}
              </el-tag>
            </el-space>
          </div>
          
          <!-- 教案内容 -->
          <div class="lesson-content">
            <h2 class="content-title">教案内容</h2>
            <div class="content-body" v-html="renderContent(lessonPlan.content)"></div>
          </div>
          
          <!-- 附件列表 -->
          <div class="lesson-attachments" v-if="lessonPlan.attachments && lessonPlan.attachments.length > 0">
            <h2 class="section-title">附件文件</h2>
            <div class="attachment-list">
              <div
                v-for="(attachment, index) in lessonPlan.attachments"
                :key="index"
                class="attachment-item"
              >
                <span>📎</span>
                <a :href="getAttachmentUrl(attachment)" target="_blank" class="attachment-link">
                  {{ getFileName(attachment) }}
                </a>
                <el-button 
                  type="primary" 
                  size="small" 
                  link 
                  @click="downloadAttachment(attachment)"
                >
                  下载
                </el-button>
              </div>
            </div>
          </div>
          
          <!-- 版本历史 -->
          <div class="version-history" v-if="versions.length > 0">
            <h2 class="section-title">版本历史</h2>
            <el-timeline>
              <el-timeline-item
                v-for="version in versions"
                :key="version._id"
                :timestamp="formatDate(version.createdAt)"
                placement="top"
              >
                <el-card shadow="hover">
                  <div class="version-info">
                    <span class="version-number">版本 {{ version.version }}</span>
                    <span class="version-user">{{ version.modifiedBy.name }}</span>
                    <p class="version-summary" v-if="version.changesSummary">
                      {{ version.changesSummary }}
                    </p>
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click="viewVersion(version.version)"
                    >
                      查看该版本
                    </el-button>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
          
          <!-- 操作按钮 -->
          <div class="action-section">
            <el-button
              type="primary"
              :loading="liking"
              @click="handleLike"
            >
              ⭐ {{ liked ? '已赞' : '点赞' }} ({{ lessonPlan.likes || 0 }})
            </el-button>
            <el-button
              @click="handleShare"
            >
              📤 分享
            </el-button>
            <el-button
              @click="handleDownload"
            >
              📥 下载教案
            </el-button>
          </div>
        </div>
      </el-main>
      
      <!-- 空状态 -->
      <el-main v-else-if="!loading">
        <el-empty description="教案不存在或已被删除" />
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { lessonPlanApi, type LessonPlan } from '@/api/lessonPlan'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 数据状态
const loading = ref(false)
const lessonPlan = ref<LessonPlan | null>(null)
const versions = ref<any[]>([])
const liked = ref(false)
const liking = ref(false)

// 权限判断 - 只有作者可以看到编辑删除按钮
const canEdit = computed(() => {
  if (!lessonPlan.value || !authStore.user) return false
  
  // authStore.user使用id字段，lessonPlan.author使用_id字段
  return lessonPlan.value.author._id === authStore.user.id
})

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 渲染内容（支持Markdown或HTML）
const renderContent = (content: string) => {
  // 这里可以集成markdown-it或其他渲染库
  // 目前简单处理换行
  return content.replace(/\n/g, '<br>')
}

// 获取文件名
const getFileName = (path: string) => {
  return path.split('/').pop() || path
}

// 获取附件完整URL
const getAttachmentUrl = (path: string) => {
  // 如果已经是完整URL，直接返回
  if (path.startsWith('http')) {
    return path
  }
  
  // 开发环境下，由于前端运行在3007端口，需要指向后端的3008端口
  if (import.meta.env.DEV) {
    return `http://localhost:3008${path}`
  }
  
  // 生产环境下使用相对路径（通过Nginx代理）
  const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
  return baseUrl ? `${baseUrl}${path}` : path
}

// 下载附件
const downloadAttachment = async (path: string) => {
  try {
    const url = getAttachmentUrl(path)
    const link = document.createElement('a')
    link.href = url
    link.download = getFileName(path)
    link.target = '_blank'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 加载教案详情
const loadLessonPlan = async () => {
  loading.value = true
  try {
    const id = route.params.id as string
    const { data } = await lessonPlanApi.getById(id)
    lessonPlan.value = data
    
    // 设置是否已点赞
    liked.value = data.isLiked || false
    
    // 加载版本历史
    loadVersionHistory()
  } catch (error: any) {
    ElMessage.error(error.message || '加载教案失败')
    router.push('/lesson-plans')
  } finally {
    loading.value = false
  }
}

// 加载版本历史
const loadVersionHistory = async () => {
  try {
    const id = route.params.id as string
    const { data } = await lessonPlanApi.getVersionHistory(id, { limit: 10 })
    versions.value = data.versions || []
  } catch (error) {
    console.error('加载版本历史失败:', error)
  }
}

// 查看特定版本
const viewVersion = async (version: number) => {
  try {
    const id = route.params.id as string
    const { data } = await lessonPlanApi.getSpecificVersion(id, version)
    // 可以在弹窗中显示版本内容
    ElMessage.info('版本查看功能开发中')
  } catch (error: any) {
    ElMessage.error(error.message || '加载版本失败')
  }
}

// 返回列表
const handleBack = () => {
  // 检查是否有上一页历史记录
  if (window.history.length > 1) {
    // 有历史记录，返回上一页
    router.back()
  } else {
    // 没有历史记录（直接访问）
    // 如果是当前用户的教案，返回我的教案页；否则返回公开教案页
    if (lessonPlan.value && authStore.user?._id === lessonPlan.value.author._id) {
      router.push('/lesson-plans')
    } else {
      router.push('/public-lessons')
    }
  }
}

// 编辑教案
const handleEdit = () => {
  if (lessonPlan.value) {
    router.push(`/lesson-plans/${lessonPlan.value._id}/edit`)
  }
}

// 删除教案
const handleDelete = async () => {
  if (!lessonPlan.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除教案《${lessonPlan.value.title}》吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await lessonPlanApi.delete(lessonPlan.value._id)
    ElMessage.success('删除成功')
    router.push('/lesson-plans')
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 点赞
const handleLike = async () => {
  if (!lessonPlan.value) return
  
  liking.value = true
  try {
    const response = await lessonPlanApi.toggleLike(lessonPlan.value._id)
    if (response.success) {
      liked.value = response.data.liked
      lessonPlan.value.likes = response.data.likes
      ElMessage.success(response.data.liked ? '点赞成功' : '取消点赞')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    liking.value = false
  }
}

// 分享
const handleShare = () => {
  // 复制链接到剪贴板
  const url = window.location.href
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 下载教案
const handleDownload = () => {
  // TODO: 实现教案下载功能
  ElMessage.info('下载功能开发中')
}

// 页面加载时初始化
onMounted(() => {
  loadLessonPlan()
})
</script>

<style scoped>
.lesson-plan-detail {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.detail-header {
  background: white;
  padding: 0;
  height: auto !important;
  border-bottom: 1px solid #e4e7ed;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 头部按钮优化 */
.header-content .el-button {
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
}

.action-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
}

.el-main {
  padding: 0;
}

.detail-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
  background: white;
}

.lesson-header {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e4e7ed;
}

.lesson-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-tag {
  font-size: 14px;
  font-weight: normal;
}

.lesson-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  margin-bottom: 16px;
  color: #606266;
  font-size: 14px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.meta-item span:first-child {
  margin-right: 6px;
  font-size: 16px;
}

.stat-item span:first-child {
  margin-right: 6px;
  font-size: 16px;
}

.attachment-item span:first-child {
  margin-right: 8px;
  font-size: 16px;
}

.lesson-stats {
  display: flex;
  gap: 24px;
  color: #909399;
  font-size: 14px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.lesson-categories {
  margin-bottom: 20px;
}

.lesson-categories .el-tag {
  font-size: 14px;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

/* 标签内容居中 */
:deep(.lesson-categories .el-tag) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

:deep(.lesson-tags .el-tag) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

.lesson-tags {
  margin-bottom: 32px;
}

.lesson-content {
  margin-bottom: 40px;
}

.content-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}

.content-body {
  font-size: 16px;
  line-height: 1.8;
  color: #606266;
  white-space: pre-wrap;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

.lesson-attachments {
  margin-bottom: 40px;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  transition: background-color 0.3s;
  justify-content: space-between;
}

.attachment-item:hover {
  background-color: #e6e8eb;
}

.attachment-link {
  color: #409eff;
  text-decoration: none;
}

.attachment-link:hover {
  text-decoration: underline;
}

.version-history {
  margin-bottom: 40px;
}

.version-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.version-number {
  font-weight: 600;
  color: #303133;
}

.version-user {
  color: #606266;
  font-size: 14px;
}

.version-summary {
  color: #909399;
  font-size: 14px;
  margin: 8px 0 0 0;
}

.action-section {
  display: flex;
  gap: 12px;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
  align-items: center;
}

.action-section .el-button {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 按钮样式优化 - 简化版 */
:deep(.el-button) {
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
  gap: 6px !important;
}

:deep(.el-button .el-icon) {
  flex-shrink: 0 !important;
}

/* 特别处理圆形按钮 */
:deep(.el-button.is-circle) {
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-timeline-item__wrapper) {
  padding-left: 32px;
}

:deep(.el-card) {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}
</style>